//
//  ECSTableView.m
//  ECS DevelopKit
//
//  Created by LittoCats on 9/3/14.
//  Copyright (c) 2014 Littocats. All rights reserved.
//

#import "ECSTableView.h"
#import "UIKit+ECS.h"
#import "ECSUIDelegate+UITableView.h"

#import "ECSUIBuilder.h"

#import "ECSObjectAttributeWrapper.h"

@interface ECSTableView () <ECSAutoLayoutProtocol>

/**
 *  仅在自动布局，且高度为wrap_content时，有效
 */
#define kWrap_contentConstraintsHeightKey @"kWrap_contentConstraintsHeightKey"
@property (nonatomic, strong) NSMapTable *wrap_contentConstraintsTable;

@end

@implementation ECSTableView

- (id)initWithFrame:(CGRect)frame
{
    NSString *style = [self.ecsAttributes objectForKey:@"style"];
    self = [super initWithFrame:frame style:[[style lowercaseString] isEqualToString:@"group"] ? UITableViewStyleGrouped : UITableViewStylePlain];
    if (self) {
        self.wrap_contentConstraintsTable = [NSMapTable strongToWeakObjectsMapTable];
        
        self.delegate = [ECSUIDelegate defaultInstance];
        self.dataSource = [ECSUIDelegate defaultInstance];
        
        self.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return self;
}

- (void)refresh:(NSArray *)data
{
    ECS_WrapObjectAttribute(self, data, ECSUITableViewDataSourceKey);
    [self reloadData];
    
    if ([self.ecsAttributes[@"size"][@"height"] isEqual:@"wrap_content"] && self.translatesAutoresizingMaskIntoConstraints == NO) {
        [[self.wrap_contentConstraintsTable objectForKey:kWrap_contentConstraintsHeightKey] setConstant:self.contentSize.height];
        [self setNeedsUpdateConstraints];
    }
}

- (void)onItemClick:(id)callback
{
    ECS_WrapObjectAttribute(self, callback, ECSItemClickedAtIndexKey);
}

//backgroundcolor
- (void)setBackgroundColor:(UIColor *)backgroundColor
{
    if (!self.backgroundView)
        self.backgroundView = [UIView new];
    self.backgroundView.backgroundColor = backgroundColor;

}

// 自适应 高度
- (void)ecs_AutoLayoutWrapContentHeight
{
#warning contentSize 在reloadData之后可能没有及时更新
    CGFloat contentHeight = self.contentSize.height;
    NSLayoutConstraint *wrap_contentHeight = [NSLayoutConstraint constraintWithItem:self
                                                                          attribute:NSLayoutAttributeHeight
                                                                          relatedBy:NSLayoutRelationEqual
                                                                             toItem:nil
                                                                          attribute:NSLayoutAttributeNotAnAttribute
                                                                         multiplier:1
                                                                           constant:contentHeight];
    [self.wrap_contentConstraintsTable setObject:wrap_contentHeight forKey:kWrap_contentConstraintsHeightKey];
    [self addConstraint:wrap_contentHeight];
}
@end
